package com.example.sell_qq.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.CallLog;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.example.sell_qq.constant.CallLogConstant;
import com.example.sell_qq.entity.Record;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class RecordUtils {

    /**
     * 利用系统CallLog获取通话历史记录
     * @param activity
     * @return
     */
    public static List<Record> getCallHistoryList(Context context, Activity activity, int num) {
        List<Record> records = new ArrayList<>();
        String androidId = AppUtils.getAndroidID(context);
        Cursor cs;
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_CALL_LOG}, 1000);
        }
        int hasWriteContactsPermission = ActivityCompat.checkSelfPermission(context,
                Manifest.permission.WRITE_CONTACTS);
        if(hasWriteContactsPermission !=
                PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(activity, new String[]
                            {Manifest.permission.WRITE_CONTACTS},
                    123);
            return null;
        }
        cs = activity.getContentResolver().query(CallLog.Calls.CONTENT_URI, //系统方式获取通讯录存储地址
                new String[]{
                        CallLog.Calls.CACHED_NAME,  //姓名
                        CallLog.Calls.NUMBER,    //号码
                        CallLog.Calls.TYPE,  //呼入/呼出(2)/未接
                        CallLog.Calls.DATE,  //拨打时间
                        CallLog.Calls.DURATION,   //通话时长
                }, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
        int i = 0;
        if (cs != null && cs.getCount() > 0) {
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String date_today = simpleDateFormat.format(date);
            for (cs.moveToFirst(); (!cs.isAfterLast()); cs.moveToNext(), i++) {
                Record record = new Record();
                String callName = cs.getString(0);  //名称
                String callNumber = cs.getString(1);  //号码
                //通话类型
                int callType = Integer.parseInt(cs.getString(2));
                CallLogConstant callTypeStr;
                switch (callType) {
                    case CallLog.Calls.INCOMING_TYPE:
                        callTypeStr = CallLogConstant.CALL_IN;
                        break;
                    case CallLog.Calls.OUTGOING_TYPE:
                        callTypeStr = CallLogConstant.CALL_OUT;
                        break;
                    case CallLog.Calls.MISSED_TYPE:
                        callTypeStr = CallLogConstant.CALL_MISS;
                        break;
                    default:
                        // 其他类型的，例如新增号码等记录不算进通话记录里，直接跳过
                        i--;
                        continue;
                }
                //拨打时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date callDate = new Date(Long.parseLong(cs.getString(3)));
                String callDateStr = sdf.format(callDate);
                if (callDateStr.equals(date_today)) { //判断是否为今天
                    sdf = new SimpleDateFormat("HH:mm");
                    callDateStr = sdf.format(callDate);
                } else if (date_today.contains(callDateStr.substring(0, 7))) { //判断是否为当月
                    sdf = new SimpleDateFormat("dd");
                    int callDay = Integer.valueOf(sdf.format(callDate));

                    int day = Integer.valueOf(sdf.format(date));
                    if (day - callDay == 1) {
                        callDateStr = "昨天";
                    } else {
                        sdf = new SimpleDateFormat("MM-dd");
                        callDateStr = sdf.format(callDate);
                    }
                } else if (date_today.contains(callDateStr.substring(0, 4))) { //判断是否为当年
                    sdf = new SimpleDateFormat("MM-dd");
                    callDateStr = sdf.format(callDate);
                }

                //通话时长
                int callDuration = Integer.parseInt(cs.getString(4));
                int min = callDuration / 60;
                int sec = callDuration % 60;
                String callDurationStr = "";
                if (sec > 0) {
                    if (min > 0) {
                        callDurationStr = min + "分" + sec + "秒";
                    } else {
                        callDurationStr = sec + "秒";
                    }
                }

                /**
                 * callName 名字
                 * callNumber 号码
                 * callTypeStr 通话类型
                 * callDateStr 通话日期
                 * callDurationStr 通话时长
                 * 请在此处执行相关UI或存储操作，之后会查询下一条通话记录
                 */
//                Log.d("Msg: ","callName"+callName);
//                Log.d("Msg: ","callNumber"+callNumber);
//                Log.d("Msg: ","callTypeStr"+callTypeStr);
//                Log.d("Msg: ","callDateStr"+callDateStr);
//                Log.d("Msg: ","callDate"+callDate);
//                Log.d("Msg: ","callDurationStr"+callDurationStr);

                record.setUserId(androidId);
                record.setName(callName == null ? "" : callName);
                record.setNumber(callNumber);
                record.setType(callType);
                record.setDate(callDate);
                record.setDuration(callDuration);
                record.setStatus(true);
                record.setCreateTime(new Date());
                records.add(record);

                if (i == num)
                    break;
            }
        }
        return records;
    }
}
